package com.caiyouxi.boss.buser.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.caiyouxi.boss.buser.mapper.*;
import com.caiyouxi.boss.buser.model.*;
import com.caiyouxi.boss.buser.service.SysUserProfileService;
import com.caiyouxi.common.Constant;
import com.caiyouxi.common.bean.QueryParams;
import com.caiyouxi.common.bean.ResData;
import com.caiyouxi.common.cache.RedisService;
import com.caiyouxi.common.exception.ErrorCode;
import com.caiyouxi.common.service.BaseService;
import com.caiyouxi.common.util.ListDistinctUtils;
import com.caiyouxi.common.util.Log;
import com.caiyouxi.common.util.MD5Util;
import com.caiyouxi.system.mapper.SettingsMapper;
import com.caiyouxi.system.service.SysSetingService;
import com.caiyouxi.user.mapper.UserProfileMapper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.caiyouxi.common.util.ListDistinctUtils.remove_same;

/**
 * Created by Administrator on 2017/10/20.
 */

@Service
public class SysUserProfileServiceImpl extends BaseService implements SysUserProfileService {

    private Logger logger = Logger.getLogger(SysUserProfileServiceImpl.class);

    @Autowired
    private SysUserProfileMapper userProfileMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SysSetingService sysSetingService;
    @Autowired
    private SysUserProfileService userProfileService;
    @Autowired
    private SysUserAccountsMapper userAccountsMapper;
    @Autowired
    private SettingsMapper settingsMapper;
    @Autowired
    private UserProfileMapper userMapper;

    /**
     * 条件查询用户信息
     * @param
     * @return
     */
    @Override
    public ResData get_user_info_list(UserListInfoBean bean) {
        //获取分页大小
        if (StringUtils.isEmpty(bean.getPagesize()) || "0".equals(bean.getPagesize())) {
            bean.setPagesize(20);
        }
        if (StringUtils.isEmpty(bean.getPages()) || "0".equals(bean.getPages())) {
            bean.setPages(0);
        }
        List<UserListInfoBean> beans = userProfileMapper.get_user_info_list(bean);
        if (!StringUtils.isEmpty(beans)) {
            for (UserListInfoBean up : beans) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                if (!StringUtils.isEmpty(up.getReg_time())) {
                    up.setReg_date(format.format(up.getReg_time()));
                }
                if (!StringUtils.isEmpty(up.getLogin_time())) {
                    up.setLogin_date(format.format(up.getLogin_time()));
                }
            }
        }
            //总数
            int totalCount = userProfileMapper.get_user_profile_count(bean);
            QueryParams pageList = new QueryParams();
            pageList.setTotal(totalCount);
            pageList.setPage(bean.getPage());
            pageList.setPage_size(bean.getPage_size());
            pageList.setList(beans);
            return page_list(pageList);
        }

    /**
     * 用户基本详情
     */
    @Override
    public ResData get_user_profile_info(UserListInfoBean bean) {
        UserListInfoBean userListInfoBean = userProfileMapper.get_user_prefile_info(bean);
        if (!StringUtils.isEmpty(userListInfoBean)) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                if (!StringUtils.isEmpty(userListInfoBean.getReg_time())) {
                    userListInfoBean.setReg_date(format.format(userListInfoBean.getReg_time()));
                }
                if (!StringUtils.isEmpty(userListInfoBean.getLogin_time())) {
                    userListInfoBean.setLogin_date(format.format(userListInfoBean.getLogin_time()));
                }
        }
        return success(userListInfoBean);
    }



    /**
     * 冻结用户
     */
    @Override
    @Transactional
    public ResData blocking_user(UserListInfoBean bean) {
        String id = bean.getObj()+"";
        try {
            if (id.contains("&")){
                String  ids []    = id.split("&");
                for(int i=0;i<ids.length;i++){
                    if (!StringUtils.isEmpty(ids[i])){
                        userMapper.delete(Integer.parseInt(ids[i]));
                    }
                }
            }else {
                userMapper.delete(Integer.parseInt(id));
            }
        }catch (Exception e){
         return failed("处理失败",null,null);
        }
        return success(null);
    }





    /**
     * 用户列表
     * @param
     * @return
     */
    @Override
    public ResData get_user_list(SysUserProfileBean bean) {
        //获取分页大小
        Integer reids_page_size = Integer.parseInt( redisService.get("sys.pagesize").toString());
        if(null!=reids_page_size)
        {
            bean.setPage_size(reids_page_size);
        }
        List<SysUserProfileBean> beans = userProfileMapper.get_user_list(bean);
        //总数
        int totalCount = userProfileMapper.get_user_count(bean);
        QueryParams pageList = new QueryParams();
        pageList.setTotal(totalCount);
        pageList.setPage(bean.getPage());
        pageList.setPage_size(bean.getPage_size());
        pageList.setList(beans);
        return success(pageList);
    }




    /**
     * 冻结用户
     * */
    @Override
    @Transactional
    public ResData delete_user(SysUserProfileBean bean) {

        try {
            bean.setRemark(-1);
            userProfileMapper.update_user_profile(bean);
            SysUserAccountsBean sysUserAccountsBean = new SysUserAccountsBean();
            sysUserAccountsBean.setRemark(-1);
            sysUserAccountsBean.setUser_id(bean.getId());
            userAccountsMapper.update_user_accounts(sysUserAccountsBean);
        }catch (Exception e){

            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(ErrorCode.USER_DELETE_ERROR.getCode(),ErrorCode.USER_DELETE_ERROR.getMsg(),null);
        }
        return success(null);

    }

    /**
     * 用户详情
     * @param
     * @return
     */
    @Override
    public ResData get_user_info(int userId) {
        SysUserProfileBean bean = userProfileMapper.get_user_info(userId);
        return success(bean);
    }

    //获取用户权限
    @Override
    public List<String> get_user_rights(SysUserProfileBean userBean) {
        //获取用户角色列
        SysUserProfileBean bean = userProfileMapper.get_sys_role_list(userBean);
        //通过角色获取用户相应权限
        List<SysRolesBean> rolesBeanList=new ArrayList();
        List<String> rightList = new ArrayList();
        List<String> userRoleList = new ArrayList();
        List<String> listTemp= new ArrayList<String>();
        if(null != bean){
            String role = bean.getRoles();
            String[] roles = ListDistinctUtils.get_rights_string(role);
            rolesBeanList = userProfileMapper.get_user_rights_list(roles);

            for(int i=0;i<rolesBeanList.size();i++){
                SysRolesBean rolesBean = rolesBeanList.get(i);
                String right = rolesBean.getRights();
                String[] rights = ListDistinctUtils.get_rights_string(right);
                rightList = Arrays.asList(rights);
                for(String  srbean:rightList){
                    userRoleList.add(srbean);
                }
            }
            //单个list去重
            listTemp= remove_same(userRoleList);
        }
        //查出用户额外表中的权限
        List<SysUserRightsBean> rightsBeanList =  userProfileMapper.get_extra_rights_list(userBean);
        List<String> rightsList = new ArrayList<>();
        for(SysUserRightsBean subean:rightsBeanList){
            String right = subean.getRights().toString();
            rightsList.add(right);
        }
        List<String> user_rights_list = ListDistinctUtils.get_remove_two_same(listTemp,rightsList);
        return user_rights_list;
    }


    //获取用户权限菜单
    @Override
    public ResData get_sys_rights_id(SysUserProfileBean userBean) {

        //获取用户的权限Lis{1,2,3,4,5}
        List<String> get_user_rights = userProfileService.get_user_rights(userBean);

        //查询一级
        List<SysRightsBean> one_list = userProfileMapper.get_sys_rights(get_user_rights);
        JSONArray array = new JSONArray();
        for(SysRightsBean srb : one_list){
            JSONObject obj = (JSONObject)JSONObject.toJSON(srb);
            //二级菜单
            List<SysRightsBean> two_list = userProfileMapper.get_sys_rights_id(srb.getId(),get_user_rights);
            JSONArray two_array = new JSONArray();
            for(SysRightsBean two_srb :two_list){
                JSONObject two_obj = (JSONObject) JSONObject.toJSON(two_srb);
                //三级菜单
                List<SysRightsBean> three_list = userProfileMapper.get_sys_rights_id(two_srb.getId(),get_user_rights);
                JSONArray three_array = (JSONArray) JSONArray.toJSON(three_list);
                two_obj.put("list",three_array);
                two_array.add(two_obj);
            }
            obj.put("list",two_array);
            array.add(obj);
        }
        return success(array);
    }

    /**
     * 新增用户
     * @param sysUserProfileBean
     * @return
     */
    @Override
    @Transactional
    public ResData add_user(SysUserProfileBean sysUserProfileBean) {

        SysUserAccountsBean sysUserAccountsBean = new SysUserAccountsBean();
        int count = 0;

        sysUserAccountsBean.setOpen_id(sysUserProfileBean.getPhone());
        count = userAccountsMapper.get_count(sysUserAccountsBean);
        if(count > 0 ){  //判断手机是否绑定
            return failed(ErrorCode.PHONE_IS_BINDING.getCode(),ErrorCode.PHONE_IS_BINDING.getMsg(),null);
        }

        sysUserAccountsBean.setOpen_id(sysUserProfileBean.getEmail());
        count = userAccountsMapper.get_count(sysUserAccountsBean);
        if(count > 0 ){ //判断邮箱是否绑定
            return failed(ErrorCode.EMAIL_IS_BINDING.getCode(),ErrorCode.EMAIL_IS_BINDING.getMsg(),null);
        }

        try {
            sysUserProfileBean.setStatus("NORMAL");
            sysUserProfileBean.setCreate_time(new Date());
            sysUserProfileBean.setOwner(Constant.OWNER_PARTNER_NO);
            logger.info(MD5Util.getRandomString(6));
            sysUserProfileBean.setUsername(MD5Util.getRandomString(6));
            sysUserProfileBean.setNickname(MD5Util.getRandomString(6));
            sysUserProfileBean.setSalt(MD5Util.createSalt().toString());
            sysUserProfileBean.setPassword_algorithm("MD5");
            sysUserProfileBean.setPassword(MD5Util.encryption(sysUserProfileBean.getPassword() + sysUserProfileBean.getSalt()));
            int result = userProfileMapper.add_user_profile(sysUserProfileBean);

            if(result == 1){
                sysUserAccountsBean.setNickname(sysUserProfileBean.getNickname());
                sysUserAccountsBean.setUser_id(sysUserProfileBean.getId());
                sysUserAccountsBean.setAuth_protocol("PASSWORD");
                sysUserAccountsBean.setBind_time(new Date());

                sysUserAccountsBean.setSource("PHONE");
                sysUserAccountsBean.setOpen_id(sysUserProfileBean.getPhone());
                userAccountsMapper.add_user_accounts(sysUserAccountsBean); //手机

                sysUserAccountsBean.setSource("EMAIL");
                sysUserAccountsBean.setOpen_id(sysUserProfileBean.getEmail());
                userAccountsMapper.add_user_accounts(sysUserAccountsBean);
            }

        } catch (Exception e){
            e.printStackTrace();
            logger.error("=========================添加用户失败=============");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(ErrorCode.SYS_FAIL.getCode(),ErrorCode.SYS_FAIL.getMsg(),null);
        }
        return success(null);
    }

    @Override
    public ResData login(String username,String passWord,JSONObject lastLoginLog) {

        SysUserProfileBean bean = userProfileMapper.get_user_by_username(username);
        if(null == bean) {
            return failed(ErrorCode.USER_NOT_FOUND.getCode(),ErrorCode.USER_NOT_FOUND.getMsg(),null);
        }else {
            if (bean.getStatus().equals("DELETED") || bean.getStatus().equals("DISABLED")){
                return failed(ErrorCode.USER_LOGIN_FORBID.getCode(),ErrorCode.USER_LOGIN_FORBID.getMsg(),null);
            }
            if(bean.getPassword().equals(MD5Util.encryption(passWord+bean.getSalt()))){
                lastLoginLog.put("attempts","-1"); //登陆成功 失败次数清空
                lastLoginLog.put("success",true);
                bean.setLast_login_log(lastLoginLog.toJSONString());
                bean.setSalt(MD5Util.createSalt().toString());
                bean.setPassword(MD5Util.encryption(passWord+bean.getSalt()));
                userProfileMapper.update_user_profile(bean);

                //加入缓存
                redisService.set(MD5Util.encryption(bean.getId().toString()+"_"+bean.getUsername()),bean,(long)1600);
                return success(bean);
            }else {

                SysUserProfileBean updateBean = new SysUserProfileBean();
                //更新登陆失败次数
                JSONObject json = JSONObject.parseObject(bean.getLast_login_log());
                String attempts = json.get("attempts").toString();
                if (StringUtils.isEmpty(attempts)){
                    lastLoginLog.put("attempts",1);
                }else if(attempts.equals("-1")){
                    lastLoginLog.put("attempts",1);
                }else {
                    int count = Integer.parseInt(attempts);
                    count++;
                    lastLoginLog.put("attempts",count);
                }

                lastLoginLog.put("success",false);
                updateBean.setId(bean.getId());
                updateBean.setLast_login_log(lastLoginLog.toJSONString());
                userProfileMapper.update_user_profile(updateBean);

                //检查是否 超过系统错误次数
                ResData resData = sysSetingService.select_is_aptcha(bean);
                return failed(ErrorCode.USER_USERNAME_PASSWORD_ERROR.getCode(),ErrorCode.USER_USERNAME_PASSWORD_ERROR.getMsg(),resData);
            }
        }

    }

    /**
     * 更新用户状态
     * @param sysUserProfileBean
     * @return
     */
    @Override
    public ResData updateUserProfile(SysUserProfileBean sysUserProfileBean) {

        int result = userProfileMapper.update_user_profile(sysUserProfileBean);
        if(result == 1){
            SysUserProfileBean bean = userProfileMapper.select_user_profile(sysUserProfileBean.getId());
            if (bean.getStatus().equals("DELETED") || bean.getStatus().equals("DISABLED")){
                //强制用户退出登陆
                redisService.remove(MD5Util.encryption(bean.getId().toString()+"_"+bean.getUsername()));
            }else {
                //加入缓存
                redisService.set(MD5Util.encryption(bean.getId().toString()+"_"+bean.getUsername()),bean,(long)1600);
            }
            return success(null);
        }else {
            return failed(ErrorCode.SYS_BUSSINESS_ERROR.getCode(),ErrorCode.SYS_BUSSINESS_ERROR.getMsg(),null);
        }
    }

    @Override
    @Transactional
    public ResData editeUserProfile(SysUserProfileBean sysUserProfileBean) {
        try {
            //更新用户信息
            userProfileMapper.update_user_profile(sysUserProfileBean);

            //更新电话。邮箱
            SysUserAccountsBean bean = new SysUserAccountsBean();
            bean.setUser_id(sysUserProfileBean.getId());
            if(!StringUtils.isEmpty(sysUserProfileBean.getPhone())){
                bean.setOpen_id(sysUserProfileBean.getPhone());
                bean.setSource("PHONE");
                userAccountsMapper.edite_user(bean);
            }
            if(!StringUtils.isEmpty(sysUserProfileBean.getEmail())){
                bean.setOpen_id(sysUserProfileBean.getEmail());
                bean.setSource("EMAIL");
                userAccountsMapper.edite_user(bean);
            }

        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return failed(ErrorCode.SYS_BUSSINESS_ERROR.getCode(),ErrorCode.SYS_BUSSINESS_ERROR.getMsg(),null);
        }
        return success(null);
    }



    @Autowired
    private SysUserProfileMapper sysUserProfileMapper;

    @Autowired
    private SysRightsMapper sysRightsMapper;

    @Autowired
    private SysUserRightsMapper sysUserRightsMapper;

    @Autowired
    private SysRolesMapper sysRolesMapper;



    /**
     *
     * 用户权限树
     *
     * */
    @Override
    public ResData to_index(Integer id) {
        List<SysRightsBean>  sysRightsBeanList = new ArrayList<>();
        /**查看用户拥有角色下的权限*/
        SysUserProfileBean sysUserProfileBean =sysUserProfileMapper.get_user_info(id);
        if (StringUtils.isEmpty(sysUserProfileBean.getRoles())){
            Log.d("用户无角色");
            return failed("false","用户无角色",null);
        }
        String str_roles =   sysUserProfileBean.getRoles();
        List<SysRolesBean>  sysRolesBeanList = new ArrayList<>();
        /**判断用户拥有角色数量*/
        if (!str_roles.contains("|")){
            String   role = str_roles;
            SysRolesBean sysRolesBean = new SysRolesBean();
            sysRolesBean.setId(Integer.parseInt(role));
            SysRolesBean   newSysRolesBean   =  sysRolesMapper.get_role_by_id(sysRolesBean);
            sysRolesBeanList.add(newSysRolesBean);
        }else {
            String [] roles   =  str_roles.split("\\|");
            for(int i = 0;i<roles.length;i++){
                SysRolesBean sysRolesBean = new SysRolesBean();
                sysRolesBean.setId(Integer.parseInt(roles[i]));
                SysRolesBean   newSysRolesBean   =  sysRolesMapper.get_role_by_id(sysRolesBean);
                sysRolesBeanList.add(newSysRolesBean);
            }
        }

        if (sysRolesBeanList.size() == 0){
            Log.d("角色为0");
        }
        for (int i = 0 ;i<sysRolesBeanList.size();i++){
            String  rights= sysRolesBeanList.get(i).getRights();
            if (StringUtils.isEmpty(rights)){
                Log.d("权限为0");
            }
            /**判断用户拥有权限数量*/
            if (!rights.contains("|")){
                SysRightsBean sysRightsBean = new SysRightsBean();
                sysRightsBean.setId(Integer.parseInt(rights));
                SysRightsBean   newSysRightsBean   =  sysRightsMapper.select_sys_rights(sysRightsBean);
                sysRightsBeanList.add(newSysRightsBean);
            }else {
                String [] user_rights   =  rights.split("\\|");
                for(int j = 0;j<user_rights.length;j++){
                    SysRightsBean sysRightsBean = new SysRightsBean();
                    sysRightsBean.setId(Integer.parseInt(user_rights[j]));
                    SysRightsBean   newSysRightsBean   =  sysRightsMapper.select_sys_rights(sysRightsBean);
                    sysRightsBeanList.add(newSysRightsBean);
                }
            }

        }
        /**查看用户特殊的权限*/
        List<SysUserRightsBean> sysUserRightsBeans   =  sysUserRightsMapper.get_sys_user_rights(id);
        for(SysUserRightsBean p: sysUserRightsBeans){
            SysRightsBean sysRightsBean = new SysRightsBean();
            sysRightsBean.setId(p.getRights());
            SysRightsBean   newSysRightsBean   =  sysRightsMapper.select_sys_rights(sysRightsBean);
            sysRightsBeanList.add(newSysRightsBean);
        }
        /**对权限进行去重处理*/
        Map<String,SysRightsBean> map = new HashMap<>();
        for( SysRightsBean p : sysRightsBeanList){
            map.put(p.getId()+"",p);
        }
        List<SysRightsBean> mapValuesList = new ArrayList<>();
        Log.d("总共有"+mapValuesList.size()+"个角色");
        for (String key : map.keySet()) {
            mapValuesList.add(map.get(key));
        }



        /**对权限树形处理*/
        //第一层
        JSONArray first_arr = new JSONArray();
        for( SysRightsBean  f: mapValuesList){
            if (f.getParent_id() == 0){
                JSONObject first_obj=(JSONObject)JSONObject.toJSON(f);


                List<SysRightsBean> second_right= getList(mapValuesList,f.getId());

                //第二层
                JSONArray  second_arr = new JSONArray();
                for( SysRightsBean  s: second_right){
                    JSONObject second_obj=(JSONObject)JSONObject.toJSON(s);

                    //第三层
                    List<SysRightsBean> Third_right= getList(mapValuesList,s.getId());
                    JSONArray  third_arr= new JSONArray();
                    for (SysRightsBean  t: Third_right){
                        JSONObject  third_obj=(JSONObject)JSONObject.toJSON(t);
                        third_arr.add(third_obj);
                    }
                    second_obj.put("third_arr",third_arr);
                    second_arr.add(second_obj) ;
                }
                first_obj.put("second_arr",second_arr);
                first_arr.add(first_obj);
            }
        }
        JSONObject right_json = new JSONObject();
        right_json.put("rights",first_arr);
        return success(right_json) ;
    }

    /**重做数据源*/
    protected  List<SysRightsBean> getList(List<SysRightsBean> lists,Integer id){
        List<SysRightsBean> mapValuesList = new ArrayList<>();
        for( SysRightsBean  list : lists){
            if ((list.getParent_id()+"").equals(id+"")){
                mapValuesList.add(list);
            }
        }
        return mapValuesList;
    }

}
